
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using ScrewTurn.Wiki.PluginFramework;

namespace ScrewTurn.Wiki {

	public partial class MessagePage : BasePage {

        protected void Page_Load(object sender, EventArgs e) {
            Page.Title = Resources.Messages.MessageTitle + " - " + Settings.WikiTitle;

			if(SessionFacade.LoginKey == null) {
				Response.Redirect("Login.aspx?Redirect=" + Tools.UrlEncode(Request.Url.ToString().Substring(Request.Url.ToString().ToLowerInvariant().IndexOf("message.aspx"))));
            }

            if(!Page.IsPostBack) {
                if(Request["Username"] != null) {
                    txtRecipient.Text = Request["Username"];
                }
				if(Request["Subject"] != null) {
					txtSubject.Text = Request["Subject"];
				}
            }
        }

        protected void btnSend_Click(object sender, EventArgs e) {
			Users u = Users.Instance;
            UserInfo user = u.Find(txtRecipient.Text);
            if(user == null) {
				if(txtRecipient.Text.Equals("admin")) {
					user = new UserInfo("admin", Settings.ContactEmail, true, DateTime.Now, true, null);
				}
				else {
					lblResult.Text = @"<span style=""color: #FF0000;"">" + Resources.Messages.UserNotFound + "</span>";
					return;
				}
            }
            if(txtSubject.Text.Length == 0 || txtBody.Text.Length == 0) {
				lblResult.Text = @"<span style=""color: #FF0000;"">" + Resources.Messages.SubjectBodyNeeded + "</span>";
                return;
            }
			UserInfo senderUser = u.Find(SessionFacade.Username);
			if(senderUser == null && (SessionFacade.Username).Equals("admin")) senderUser = new UserInfo("admin", Settings.ContactEmail, true, DateTime.Now, true, null);
			Log.LogEntry("Sending Email to " + user.Username + " from " + senderUser.Username, EntryType.General, SessionFacade.Username);
			EmailSender.Send(user.Email, "\"" + senderUser.Username + "\"" + " <" + Settings.SenderEmail + ">", txtSubject.Text, senderUser.Username + " sent you this message from " + Settings.WikiTitle + ". To reply, please go to " + Settings.MainUrl + "Message.aspx?Username=" + Tools.UrlEncode(senderUser.Username) + "&Subject=" + Tools.UrlEncode("Re: " + txtSubject.Text) + "\nPlease do not reply to this Email.\n\n" + txtBody.Text, false);
			lblResult.Text = @"<span style=""color: #009900;"">" + Resources.Messages.MessageSent + "</span>";
            txtSubject.Text = "";
            txtBody.Text = "";
        }

    }

}
